package com.example.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class EchoClientHandle implements Runnable {
    //客户端
    private SocketChannel clientChannel;
    // 循环结束标记
    private boolean flag = true;

    public EchoClientHandle(SocketChannel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    public void run() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(50);
        try {
            while (this.flag) {
                byteBuffer.clear();
                int read = this.clientChannel.read(byteBuffer);
                String msg = new String(byteBuffer.array(), 0, read).trim();
                String outMsg = "【Echo】" + msg + "\n"; // 回应信息
                if ("byebve".equals(msg)) {
                    outMsg = "会话结束，下次再见！";
                    this.flag = false;
                }
                byteBuffer.clear();
                byteBuffer.put(outMsg.getBytes());  //回传信息放入缓冲区
                byteBuffer.flip();
                this.clientChannel.write(byteBuffer);// 回传信息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
